import React, { FC, useState, ChangeEvent } from 'react'
import { Button, Typography, Space, Input, message } from 'antd'
import { useNavigate, useParams } from 'react-router-dom'
import { useDispatch } from 'react-redux'
import { LeftOutlined, EditOutlined, LoadingOutlined } from '@ant-design/icons'
import { useRequest, useKeyPress, useDebounceEffect } from 'ahooks'
import styles from './EditHeader.module.scss'
import EditToolbar from './EditToolbar'
import useGetPageInfo from '../../../hooks/useGetPageInfo'
import { changePageTitle } from '../../../store/pageInfoReducer'
import useGetComponentInfo from '../../../hooks/useGetComponentInfo'
import { updateQuestionService } from '../../../services/question'
//显示和修改标题
const TitleElem: FC = () => {
  const dispathc = useDispatch()
  const { title } = useGetPageInfo()
  const [eidtState, SetEidtState] = useState(false)
  function handleChange(e: ChangeEvent<HTMLInputElement>) {
    const newTitle = e.target.value
    if (!newTitle) return
    dispathc(changePageTitle(newTitle))
  }
  if (eidtState)
    return (
      <Input
        onChange={handleChange}
        value={title}
        onPressEnter={() => SetEidtState(false)}
        onBlur={() => SetEidtState(false)}
      />
    )
  return (
    <Space>
      <Typography.Title>{title}</Typography.Title>
      <Button type="text" icon={<EditOutlined />} onClick={() => SetEidtState(true)} />
    </Space>
  )
}
//保存按钮组件
const SaveButton: FC = () => {
  const { componetnList } = useGetComponentInfo()
  const pageInfo = useGetPageInfo()
  const { id } = useParams()

  const { loading, run: save } = useRequest(
    async () => {
      if (!id) return message.info('id不能为空')
      await updateQuestionService(id, { ...pageInfo, componetnList })
    },
    { manual: true }
  )
  // 快捷键
  useKeyPress(['ctrl.s', 'meta.s'], (e: KeyboardEvent) => {
    e.preventDefault()
    if (!loading) save()
  })
  //自动保存
  useDebounceEffect(
    () => {
      if (!loading) save()
    },
    [pageInfo, componetnList],
    { wait: 1000 }
  )
  return (
    <Button onClick={save} disabled={loading} icon={loading ? <LoadingOutlined /> : null}>
      保存
    </Button>
  )
}
//发布按钮
const PublicButton: FC = () => {
  const { componetnList } = useGetComponentInfo()
  const pageInfo = useGetPageInfo()
  const { id } = useParams()
  const nav=useNavigate()
  const { loading, run: pub } = useRequest(
    async () => {
      if (!id) return message.info('id不能为空')
      await updateQuestionService(id, { ...pageInfo, componetnList,isPublished:true })
    },
    { 
      manual: true,
      onSuccess(){
        message.success('发布成功')
        nav('/question/stat/'+id) //发布成功跳转到统计页面
      }
     }
  )
  return <Button type="primary" onClick={pub} disabled={loading} icon={loading ? <LoadingOutlined /> : null}  >发布</Button>
}
//编辑器头部
const EditHeader: FC = () => {
  const nav = useNavigate()

  return (
    <div className={styles['header-wrapper']}>
      <div className={styles.header}>
        <div className={styles.left}>
          <Space>
            <Button type="link" icon={<LeftOutlined />} onClick={() => nav(-1)}>
              返回
            </Button>
            <TitleElem />
          </Space>
        </div>
        <div className={styles.main}>
          <EditToolbar />
        </div>
        <div className={styles.right}>
          <Space>
            <SaveButton />
            <PublicButton />
          </Space>
        </div>
      </div>
    </div>
  )
}
export default EditHeader
